// pages/leave/leave.js
const app = getApp()
var server = app.globalData.server;
var appid = app.globalData.appid;

Page({

    /**
     * 页面的初始数据
     */
    data: {
        pages: 1,
        currentPage: 1,
        size:20,
        userInfo: {},
        inputValue: '',
        img_url: app.globalData.cloud_url,
        auth: false,
        msgSta: false,
        signSta: false,
        chatList:[],
        chatNum:0
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: function(options) {
        var that = this
        let userInfo = wx.getStorageSync('userInfo')
        if (userInfo) {
            this.setData({
                auth: true,
                userInfo: userInfo
            })
        }
      that.getData();
    },
  getData(){
    //查询数据
    wx.showLoading({ //期间为了显示效果可以添加一个过度的弹出框提示“加载中”  
      title: '加载中',
      icon: 'loading',
    });
    var that =this;
    const db = wx.cloud.database()
    // 查询当前用户所有的 leave_user
    db.collection('leave_audit').count({
        success: function (res) {
          wx.hideLoading();
        console.log(res.total)
        that.setData({
          chatNum: res.total,
          pages: Math.ceil(res.total / that.data.size)
        })
          console.log(that.data.pages)

          db.collection('leave_audit').where({})
            .skip(that.data.size * (that.data.currentPage-1) )
            .limit(that.data.size) // 限制返回数量
            .orderBy('leave_time', 'desc')  // desc 倒 asc 正
            .get({
              success: res => {
                var chatList = that.data.chatList
                 for (var i=0 ;i<res.data.length;i++){
                   chatList.push(res.data[i])
                 }
                that.setData({
                  chatList: chatList
                })
              
              },
              fail: err => {
                wx.showToast({
                  icon: 'none',
                  title: '获取数据失败失败'
                })
                console.error('[数据库] [查询记录] 失败：', err)
              }
            })
        }
      })
  
  },
  /**
 * 页面上拉触底事件的处理函数
 */
  onReachBottom: function () {
    if (this.data.pages <= this.data.currentPage) {
      wx.showToast({
        title: '无更多数据',
        icon: 'none',
        duration: 1000
      });
    } else {
      this.setData({
        currentPage: this.data.currentPage + 1
      })
      this.getData();
    }
  },
    leaveMsg: function() {
        this.setData({
            msgSta: true,
            signSta: false
        })
    },
    signIn: function() {
        this.setData({
            signSta: true,
            msgSta: false
        })
    },
    cancelMsg: function() {
        this.setData({
            signSta: false,
            msgSta: false
        })
    },

    formSubmit(event) {
        var that = this

        var userInfo = that.data.userInfo;
      var nickName = userInfo.nickName;
      var avatarUrl = userInfo.avatarUrl;

        var name = event.detail.value.name;
        if (name == '' ) {
            wx.showToast({
                title: '请填写您的姓名',
                icon: 'none'
            })
            return;
        }
        var tel = event.detail.value.tel;
        if (tel == '') {
            wx.showToast({
                title: '请填写您的电话',
                icon: 'none'
            })
            return;
        }
        var reg_tel = new RegExp('^(13[0-9]|14[579]|15[0-3,5-9]|16[6]|17[0135678]|18[0-9]|19[89])\\d{8}$');
      var myregName = /^[\u4E00-\u9FA5\uf900-\ufa2d]{2,4}$/
      if (!myregName.test(name)){
        wx.showToast({
          title: '请填写正确的姓名',
          icon: 'none'
        })
        return;
        }
        if (!reg_tel.test(tel)) {
            wx.showToast({
                title: '请填写正确的手机号码',
                icon: 'none'
            })
            return;
        }
        var plan_people = event.detail.value.plan;
        var desc = event.detail.value.extra;
        var json ={
          plan_people,
          desc,
          tel,
          name
        }
      console.log(json)
      //增加出席
      const db = wx.cloud.database()
      db.collection('accept_user').add({
        data: json,
        success: res => {
          // 在返回结果中会包含新创建的记录的 _id
          console.log(res)
          wx.showToast({
            title: '出席成功',
            duration: 2000,
            complete: function () {
              setTimeout(function(){
                that.cancelMsg()
              },1000)
            }
          })
        },
        fail: err => {
          wx.showToast({
            icon: 'none',
            title: '出席失败'
          })
          console.error('[数据库] [新增记录] 失败：', err)
        }
      })
    },
    bindKeyInput: function(e) {
        this.setData({
            inputValue: e.detail.value
        })

    },
    bindgetuserinfo: function(e) {
        console.log(e.detail.userInfo)
        var that = this;
        if (e.detail.userInfo) {
            wx.setStorageSync('userInfo', e.detail.userInfo)
            that.setData({
                userInfo: e.detail.userInfo,
                auth: true
            })
          wx.showToast({
            title: '授权成功',
            duration: 2000,
            success:function(){
              setTimeout(function () {
                wx.showToast({
                  title: "你可以留言评论啦~",
                  icon: 'none',
                  duration: 2000
                });
              }, 2000)
            }
          })
         
        } else {
            wx.showToast({
                title: "为了您更好的体验,请先同意授权",
                icon: 'none',
                duration: 2000
            });
        }
    },
    foo: function() {
        var that = this
        console.log(that.data.inputValue)

      if (that.data.inputValue.replace(/(^\s*)|(\s*$)/g, "")) {
            //留言内容不是空值
            var userInfo = that.data.userInfo;
            var nickName = userInfo.nickName;
            var avatarUrl = userInfo.avatarUrl;
            var content = that.data.inputValue;
          var leave_time = new Date(+new Date() + 8 * 3600 * 1000).toISOString().replace(/T/g, ' ').replace(/\.[\d]{3}Z/, '')
          //增加留言
          const db = wx.cloud.database()
          db.collection('leave_audit').add({
            data: {
              nickName,
              avatarUrl,
              content,
              leave_time
            },
            success: res => {
              // 在返回结果中会包含新创建的记录的 _id
             console.log(res)
              wx.showToast({
                title: '留言成功',
                duration:2000,
                complete: function () {
                  setTimeout(function () {
                    that.cancelMsg()
                    that.setData({
                      currentPage: 1,
                      chatList: []
                    })
                    that.getData()
                  }, 1000)
                }
              })
             
            },
            fail: err => {
              wx.showToast({
                icon: 'none',
                title: '留言失败'
              })
              console.error('[数据库] [新增记录] 失败：', err)
            }
          })
        } else {
            //Catch Error
            wx.showToast({
                title: '您还没有填写内容',
                icon: 'none'
            })
            return;
        }
        that.setData({
            inputValue: '' //将data的inputValue清空
        });
        return;
    },
  /**
* 用户点击右上角分享
*/
  onShareAppMessage: function () {
    var that = this;
    //console.log(that.data);
    return {
      title: '婚礼邀请函',
      path: 'pages/Wedding/Wedding',
      success: function (res) {
        wx.showToast({
          title: '分享成功',
        })
      },
      fail: function (res) {
        // 转发失败
        wx.showToast({
          title: '分享取消',
        })
      }
    }
  },
  //下拉刷新
  onPullDownRefresh: function () {
    var that = this
    setTimeout(function () {
      wx.stopPullDownRefresh() //停止刷新
      that.setData({
        currentPage:1,
        chatList:[]
      })
      that.onLoad()
    }, 1000);
  },
})